package cn.steam.foo.service.impl;

import cn.steam.bar.model.WeaponCreateModel;
import cn.steam.bar.model.WeaponVO;
import cn.steam.foo.feign.WeaponFeign;
import cn.steam.foo.model.TaskResult;
import cn.steam.foo.service.WeaponService;
import cn.steam.foo.taks.Task;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @author zhang jintao on 2022/05/15
 **/
@Service
public class WeaponServiceImpl implements WeaponService {

    private static final List<String> types = Arrays.asList(
            "机枪",
            "步枪",
            "手枪",
            "刀具",
            "投掷武器",
            "防弹衣",
            "补给品",
            "狙击枪"
    );

    @Autowired
    WeaponFeign weaponFeign;
    @Autowired
    ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public WeaponVO getById(Integer id) {
        return weaponFeign.getById(id);
    }

    @Override
    public String addBatch(Integer num) {
        String taskId = UUID.randomUUID().toString();
        Random random = new Random();
        TaskResult result = new TaskResult();
        result.setTaskId(taskId);
        result.setTotal(num);
        for (int i = 0; i < num; i++) {
            WeaponCreateModel model = WeaponCreateModel.builder()
                    .name(UUID.randomUUID().toString())
                    .type(types.get(random.nextInt(types.size()))).build();
            Task task = new Task();
            task.setWeaponFeign(weaponFeign);
            task.setModel(model);
            task.setResult(result);
            task.setRedisTemplate(redisTemplate);
            taskExecutor.execute(task);
        }
        return taskId;
    }

    @Override
    public TaskResult look(String taskId) {
        String json = redisTemplate.opsForValue().get(taskId);
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        return JSON.parseObject(json, TaskResult.class);
    }

}

